package com.example.Http_Android;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int GET_RESULT = 1001;
    private Button btnHttpGet;
    private Button btnHttpPost;
    private EditText editText;
    private TextView txtResult;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what==GET_RESULT){
                    String html = (String) msg.obj;
                    txtResult.setText(html);
                    return true;
                }
                return false;
            }
        });

        btnHttpGet = findViewById(R.id.btn_httpget);
        btnHttpPost = findViewById(R.id.btn_httppost);
        txtResult = findViewById(R.id.txt_phone);
        editText = findViewById(R.id.edt_phone);

        btnHttpGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        userHttpGet(phone);
                    }
                }).start();
            }
        });

        btnHttpPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        userHttpPost(phone);
                    }
                }).start();
            }
        });

    }

    private void userHttpPost(String phone) {
        String url="http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        //建立HttpPost对象   发送post 请求
        HttpPost httpPost = new HttpPost(url);
        // 获取当前客户端对象
        HttpClient httpClient = new DefaultHttpClient();

        //建立一个NameValuePair数组，用于存储欲传送的参数
        List<NameValuePair> nameValuePairs = new ArrayList<>();

        //添加参数
        nameValuePairs.add(new BasicNameValuePair("mobileCode",phone));
        nameValuePairs.add(new BasicNameValuePair("userID",""));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            //通过请求对象获取响应对象
            HttpResponse httpResponse = httpClient.execute(httpPost);

            //用post从android 手机端向服务器发送数据
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
            Log.e(TAG,htmlContent);

            //  这里txtResult.setText(htmlContent)会报错，需要Message传出数据
            Message message = new Message();
            message.what = GET_RESULT;
            message.obj = htmlContent;
            handler.sendMessage(message);
        }catch(IOException e){
                e.printStackTrace();
            }

    }


    private void userHttpGet(String phone) {
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=";
        url = url.concat(phone).concat("&userID=");
        // 获取当前客户端对象
        HttpClient httpClient = new DefaultHttpClient();
        // 创建HttpGet实例
        HttpGet httpGet = new HttpGet(url);

        try {
            //连接到服务器
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //获取状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG,"code= "+code);

           // 用get从android手机端向服务器端发送数据
          //  String htmlContent = getHtmlContent(httpResponse);
            //Log.e(TAG,htmlContent);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
            Log.e(TAG,htmlContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//    将请求结果转换成String类型    从输入流中读取数据
    private String getHtmlContent(HttpResponse httpResponse) throws IOException {
        //获取网站数据？  获取到流
        InputStream inputStream = httpResponse.getEntity().getContent();
        BufferedReader bufferedReader = new BufferedReader(new BufferedReader(new InputStreamReader(inputStream)));
        StringBuffer stringBuffer = new StringBuffer();
        String line = bufferedReader.readLine();
        while(line!=null){
            stringBuffer.append(line);
            line = bufferedReader.readLine();
        }
        inputStream.close();
        bufferedReader.close();
        return stringBuffer.toString();

    }
}
